package com.prj.ufdm.bsplatform.bpo._impl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONArray;
import com.insigma.odin.framework.ucenter.InfoDTO;
import com.insigma.odin.framework.ucenter.LoginException;
import com.insigma.odin.framework.ucenter.ResponseMessage;
import com.insigma.odin.framework.ucenter.VeryCodeReturn;
import com.insigma.odin.framework.ucenter.util.AESCoder;
import com.insigma.odin.framework.ucenter.util.ByteToStringUtil;
import com.insigma.odin.framework.ucenter.util.RsaUtil;
import com.prj.ufdm.bsplatform.bpo.BspfFunctionBPO;
import com.prj.ufdm.bsplatform.bpo.BsplatformBPO;
import com.prj.ufdm.bsplatform.model.BspfParam;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

@Service
public class BsplatformBPOImpl implements BsplatformBPO {

	@Autowired
	BspfFunctionBPO bspfFunctionBPO;
	
	@Override
	public void responseTreeNode(HttpServletRequest request, HttpServletResponse response, String userId) throws Exception {
		JSONArray jsonArray = bspfFunctionBPO.doGetBspfFunctionJson(userId);
		InfoDTO info = new InfoDTO();
        info.setObj(jsonArray);
        info.setResult("1");
   		this.ajaxResponse(request, response, info);
	}
	
	/**
	 * DESC: 返回验证码
	 * @auther 胡义振
	 * @date 2020年4月29日
	 * @param request
	 * @param response
	 * @throws Exception 
	 * @return
	 */
	@Override
	public void responseVerifyCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
	    String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";//含有字符和数字的字符串
        Random random = new Random();//随机类初始化
        StringBuffer sb = new StringBuffer();//StringBuffer类生成，为了拼接字符串
        for (int i = 0; i < 4; i++) {
            int number = random.nextInt(62);// [0,62)
            sb.append(str.charAt(number));
        }
   		VeryCodeReturn ret = new VeryCodeReturn();
   		ret.setVeryCode(sb.toString());
   		ResponseMessage resObj=new ResponseMessage();
   		resObj.setData(ret);
   		resObj.setMessageCode("0");
   		request.getSession().setAttribute("verifycode",sb.toString());
   		this.ajaxResponse(request, response, resObj);
	}
	
	
	@Override
	public void responseOk(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ResponseMessage resObj =new ResponseMessage();
		resObj.setMessageCode("0");
		resObj.setData(null);
		resObj.setMainMessage("");
		this.ajaxResponse(request, response, resObj);
	}
	
	@Override
	public void responseVerifyCodeErr(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ResponseMessage resObj=new ResponseMessage();
		resObj.setMessageCode("1");
		resObj.setMainMessage("授权码验证出错！");
		this.ajaxResponse(request, response, resObj);
	}
	
	/**
	 * DESC: 获取请求参数
	 * @auther 胡义振
	 * @date 2020年4月29日
	 * @param request
	 * @return
	 * @throws Exception 
	 * @return
	 */
	@Override
	public BspfParam getLoginParam(HttpServletRequest request) throws Exception {
		BspfParam bspfParam = new BspfParam();
		bspfParam.setYyid(request.getParameter("yyid"));
		bspfParam.setMethod(request.getParameter("method"));
		if(request.getSession()!=null && request.getSession().getAttribute("verifycode")!=null) {
		    bspfParam.setSessionVerifycode(request.getSession().getAttribute("verifycode").toString());
		}
		String paramStr = request.getParameter("param");
		if(paramStr!=null && !paramStr.equals("")) {
			bspfParam.setParamStr(paramStr);
			String paramDecode = RsaUtil.deciphering(paramStr);
			JSONObject paramJson = JSONObject.fromObject(paramDecode);
			if(paramJson!=null) {
				BspfParam.Param param = bspfParam.new Param();
				String loginnameStr = paramJson.get("loginname")!=null ? paramJson.get("loginname").toString() : "";
				param.setLoginnameStr(loginnameStr);
				param.setLoginname(getLoginName(loginnameStr));
				param.setPassword(paramJson.get("password")!=null ? paramJson.get("password").toString() : "");
				param.setScode(paramJson.get("scode")!=null ? paramJson.get("scode").toString() : "");
				param.setTtime(paramJson.get("ttime")!=null ? paramJson.get("ttime").toString() : "");
				bspfParam.setParam(param);
			}
		}
		return bspfParam;
	}
	
	private String getLoginName(String loginnameStr) throws Exception {
		AESCoder aes = new AESCoder();
		byte encryptData[] = ByteToStringUtil.hexStringToBytes(loginnameStr);					
		byte byts_data[] = AESCoder.decrypt(encryptData, aes.toKey());					
		String newString = new String(byts_data, "GBK");
		loginnameStr = newString.split("=")[1];
		return loginnameStr;
	}
	
	private void ajaxResponse(HttpServletRequest request, HttpServletResponse response, Object obj) throws LoginException{
	        try{
	            response.setContentType("text/plain;charset="+"GBK");
	            PrintWriter printwriter = response.getWriter();
	            JsonConfig jsonConfig = new JsonConfig();
	            jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
	            printwriter.println(JSONObject.fromObject(obj, jsonConfig));
	            printwriter.flush();
	            printwriter.close();
	        }catch(IOException ioexception){
	            throw new LoginException("系统错误：返回JSON数据时出现IO错误", ioexception);
	        }
	}

}
